import * as types from '../types'
import axios from 'axios'

const state = {
  lessons: [],
  total: 0
}

const getters = {
  lessons: state => state.lessons,
  totalLessons: state => state.total
}

const mutations = {
  [types.LESSONS_LOADED](state, data) {
    state.total = data.total || 0
    state.lessons = data.courses || []
  }
}

const actions = {
  async searchLessons({
    commit
  }, query) {
    let response = await axios.post('/vts/search/courses', query)
    commit(types.LESSONS_LOADED, response.data)
  },
  async saveLesson({
    commit
  }, data) {
    let response = await axios.post('/vts/course/save', data.form)
    if (response.data.saved) data.callback()
  },
  async updateSticky({
    commit
  }, data) {
    let response = await axios.post('/vts/course/updateSticky', data.model)
    if (response.data.accepted) data.callback()
  },
  async removeLesson({
    commit
  }, data) {
    let response = await axios.post('/vts/course/remove', {
      id: data.id
    })
    if (response.data.removed) data.callback()
  },
  async getLesson({
    commit
  }, data) {
    let response = await axios.get('/vts/course/get/' + data.id)
    if (response.status === 200 && response.data.success !== false) data.callback(response.data)
  },
  async getTop6Courses({
    commit
  }, data) {
    let response = await axios.get('/vts/course/GetTop6Courses?orderBy=' + data.orderBy)
    if (response.status === 200) data.callback(response.data)
  },
  async getRelatedCourses({
    commit
  }, data) {
    let response = await axios.get('/vts/course/getRelatedCourses?id=' + data.id)
    if (response.status === 200) data.callback(response.data)
  }
}

export default {
  state,
  mutations,
  getters,
  actions
}
